
// AES-256-GCM 认证加密模式
// 密钥生成
export async function generateKey() {
    return await window.crypto.subtle.generateKey(
      {
        name: "AES-GCM",
        length: 256, // 256位密钥
      },
      true, // 是否可导出
      ["encrypt", "decrypt"] // 密钥用途
    );
  }


//   加密
//   plaintext 需要加密的字符串  key 密钥
export async function encryptData(plaintext, key) {
    // 生成初始化向量(IV) - 通常为12字节
    const iv = window.crypto.getRandomValues(new Uint8Array(12));
    
    const ciphertext = await window.crypto.subtle.encrypt(
      {
        name: "AES-GCM",
        iv: iv,
        tagLength: 128, // 认证标签长度
      },
      key,
      new TextEncoder().encode(plaintext)
    );
    
    return {
      iv: Array.from(iv).join(','), // 将IV转换为可传输格式
      ciphertext: Array.from(new Uint8Array(ciphertext)).join(','),
    };
  }

//   解密
// encryptedData 需要解密的字符串 key 密钥
export async function decryptData(encryptedData, key) {
    const iv = new Uint8Array(encryptedData.iv.split(',').map(Number));
    const ciphertext = new Uint8Array(encryptedData.ciphertext.split(',').map(Number));
    
    const plaintext = await window.crypto.subtle.decrypt(
      {
        name: "AES-GCM",
        iv: iv,
        tagLength: 128,
      },
      key,
      ciphertext
    );
    
    return new TextDecoder().decode(plaintext);
}
export default {
    generateKey,
    encryptData,
    decryptData
}